package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

@SuppressLint("UseValueOf")
public class EachProfileActivity extends Activity {
	private ImageButton btnTalk, favorite, station, board;
	private TextView title, nickname, introduction, favorite_num;
	private ImageView back, userPhoto;
	private String user_id;
	private TextView favorite_state;
	private String check;
	private Bitmap image;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.each_profile_home);
        
        Intent intent = getIntent();
        back = (ImageView) findViewById(R.id.btnBack);
        userPhoto = (ImageView) findViewById(R.id.userPhoto);
        try{
        	user_id = intent.getExtras().get("user_id").toString();
        } catch (Exception e) {
        	user_id = Preferences.getValue(getBaseContext(), "user_id");
		}
        favorite_state = (TextView)findViewById(R.id.textProfile);
        favorite_num = (TextView)findViewById(R.id.favorite_num);
		title = (TextView)findViewById(R.id.peopleName);
		nickname = (TextView)findViewById(R.id.userNickname);
		introduction = (TextView)findViewById(R.id.userProfile);
        
        btnTalk = (ImageButton)findViewById(R.id.btnTalk);
        favorite = (ImageButton)findViewById(R.id.btnShowProfile);
        station = (ImageButton)findViewById(R.id.btnShowSchedule);
        board = (ImageButton)findViewById(R.id.btnShowStationAbout);
        
        setClickListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setProfileView();
		for(int i = 0 ; i < 5; i++)
        	TrainTravelActivity.tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.bg_nav2);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		for(int i = 0 ; i < 5; i++)
        	TrainTravelActivity.tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.bg_nav1);
	}
	
	private void setProfileView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.userProfile, "user_id", user_id};
		task.execute(params);
	}

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			int favorite;
			if(result.equals("favorite")){
				favorite_state.setText("차단하기");
				favorite_state.setTextColor(Color.GRAY);
				check = result;
				favorite = new Integer(favorite_num.getText().toString());
				favorite_num.setText(""+(favorite+1));
			}
			else if(result.equals("deny")){
				favorite_state.setText("좋아하기");
				favorite_state.setTextColor(Color.WHITE);
				check = result;
				favorite = new Integer(favorite_num.getText().toString());
				favorite_num.setText(""+(favorite-1));
			}
		}
	}
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});

		}
	}
	
	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			JSONObject jsondata;
			try {
				response = urls[0];
				jsondata = new JSONObject(urls[0]);
				JSONObject namedata = (JSONObject) jsondata.get("user");
				if(!namedata.getString("image_url").toString().equals("") && namedata.getString("image_url") != null){
					image = LoadBitMap.fromURL(namedata.getString("image_url"));				
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			JSONObject jsondata;
			try {
				jsondata = new JSONObject(result);
				JSONObject namedata = (JSONObject) jsondata.get("user");
				int favorite = new Integer(jsondata.get("favorite").toString());
				favorite_num.setText(""+(favorite-1));
				title.setText((String)namedata.get("nick_name"));
				if(!namedata.getString("image_url").toString().equals("") && !namedata.getString("image_url").toString().equals("null")){
					userPhoto.setImageBitmap(image);
					userPhoto.setScaleType(ScaleType.FIT_XY);
				}
				if(!namedata.get("name").toString().equals("") && !namedata.get("name").toString().equals("null")){
					nickname.setText(namedata.get("name").toString());
				}
				if(!namedata.get("introduction").toString().equals("null")){
					introduction.setText(namedata.get("introduction").toString());
				}
				DownloadFavoriteAsynkTask task2 = new DownloadFavoriteAsynkTask();
				String[] params2 = new String[]{ ServerURL.favoriteCheck, "user_id", user_id,
									"deny_id", Preferences.getValue(getBaseContext(), "deny_id"),
									"favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task2.execute(params2);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


	private class DownloadFavoriteAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			check = result;
			if(check.equals("favorite")){
				favorite_state.setText("차단하기");
				favorite_state.setTextColor(Color.GRAY);
			}
		}
	}


	private class MakeTalkAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
		        JSONObject resultData = new JSONObject(result);
		        String roomId = resultData.getString("room_id");
		        Intent chatIntent = new Intent(getBaseContext(), ChatRoomActivity.class);
				chatIntent.putExtra("roomId", roomId);
				chatIntent.putExtra("isChat", true);
				startActivity(chatIntent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void setClickListener(){
		back.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btnTalk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				List<String> chatRoomUsers = new ArrayList<String>();
				chatRoomUsers.add(user_id);
				chatRoomUsers.add(Preferences.getValue(getBaseContext(), "user_id"));
				
				MakeTalkAsynkTask task = new MakeTalkAsynkTask();
				String[] params = new String[]{ ServerURL.createRoom, 
									"json_string", chatRoomUsers.toString(),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		favorite.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String url = "";
				if(check.equals("none")){
					url = ServerURL.moveToFavorite;
				}
				else if(check.equals("favorite")){
					url = ServerURL.moveFavoriteToDeny;
				}
				else if(check.equals("deny")){
					url = ServerURL.moveDenyToFavorite;
				}
				UploadAsynkTask task = new UploadAsynkTask();
				String[] params = new String[]{ url, "user_id", user_id,
									"deny_id", Preferences.getValue(getBaseContext(), "deny_id"),
									"favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		station.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), ProfileStationListActivity.class);
				intent.putExtra("user_id", user_id);
				intent.putExtra("check", check);
				((FavoriteActivity) parentActivity).startChildActivity("ProfileStation", intent);
			}
		});
		board.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), ProfileBoardActivity.class);
				intent.putExtra("user_id", user_id);
				intent.putExtra("check", check);
				((FavoriteActivity) parentActivity).startChildActivity("ProfileBoard", intent);
			}
		});
	}
	@Override
	public void onBackPressed() {
		finish();
	}
}
